import type { FC, ReactNode } from 'react'
import React, { memo } from 'react'
import Upload, { RcFile } from 'antd/es/upload'
import { Button, message } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import { reqImportExcel } from '@/service/module/main/system/user-list'
import { myShallowEqual, useMyDispatch, useMySelector } from '@/store'
import { fetchPageListAction } from '@/store/module/main/page-common'

interface IProps {
  children?: ReactNode
}

const beforeUpload = (file: RcFile) => {
  const type = 'application/vnd.ms-excel.sheet.macroEnabled.12'
  const result = file.type === type
  if (!result) {
    message.error('你只能上传 .xlsm类型的文件~')
  }
  return result
}
const UploadExcel: FC<IProps> = (props) => {
  const dispatch = useMyDispatch()
  const { searchParams } = useMySelector(
    (state) => ({
      searchParams: state.pageCommon.searchConfig
    }),
    myShallowEqual
  )

  async function handleUploadExcel({ file }: any) {
    //设置上传的参数
    const formData = new FormData()
    formData.append('file', file)
    await reqImportExcel(formData)
    dispatch(fetchPageListAction(searchParams))
  }

  return (
    <Upload
      name="excel"
      showUploadList={false}
      beforeUpload={beforeUpload}
      customRequest={handleUploadExcel}
    >
      <Button size="small" icon={<UploadOutlined />}>
        导入
      </Button>
    </Upload>
  )
}

export default memo(UploadExcel)
